<template>
  <el-container>
    <el-header height="130px">
      <h1>存档文件</h1>
      <el-row type="flex" align="middle">
        <el-col :span="6">
          <el-row>
            <el-col :span="6">
              <el-upload
                  :headers="uploadHeaders"
                  :action="uploadFileUrl"
                  :show-file-list="false"
                  :before-upload="fileUploadBeforeHandler"
                  :on-success="fileUploadSuccessHandler"
                  :on-error="fileUploadErrorHandler"
                  multiple>
                <el-button type="primary" size="mini" :loading="uploadFileButtonLoading">文件上传</el-button>
              </el-upload>
            </el-col>
            <el-col :span="12">
              <el-upload
                  ref="uploadDir"
                  name="dir"
                  :action="uploadDirUrl"
                  :show-file-list="false"
                  :http-request="uploadDirHandler"
                  :on-change="uploadDirChangeHandler"
                  multiple
                  :auto-upload="false">
                <el-button slot="trigger" size="mini" type="primary">选取文件</el-button>
                <el-button type="warning" size="mini" @click="submitUploadDir" :disabled="uploadDirButton">文件夹上传</el-button>
              </el-upload>
            </el-col>
            <el-col :span="6">
              <el-button type="info" size="mini" @click="createNewFolderCondition">新建文件夹</el-button>
              <el-dialog
                  title="新建文件夹"
                  :visible.sync="createNewFolderDialog"
                  :append-to-body="true"
                  width="30%">
                <el-form size="mini" label-width="auto" v-model="createNewFolderObj">
                  <el-form-item label="文件名：">
                    <el-input v-model="createNewFolderObj.fileName"/>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="createNewFolder">确定</el-button>
                    <el-button type="info" @click="createNewFolderDialog = false">取消</el-button>
                  </el-form-item>
                </el-form>
              </el-dialog>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="1" v-if="pasteButton">
          <el-button type="text" size="mini" @click="toPaste" :loading="pasteButtonLoading">粘贴</el-button>
        </el-col>
        <el-col :span="4">
          <el-row v-if="operateTab">
            <el-col :span="6">
              <el-button type="text" size="mini" @click="toCopyOrCut(true)">移动</el-button>
            </el-col>
            <el-col :span="6">
              <el-button type="text" size="mini" @click="toCopyOrCut(false)">复制</el-button>
            </el-col>
            <el-col :span="6">
              <el-button type="text" size="mini" @click="delFiles">删除</el-button>
            </el-col>
            <el-col :span="6">
              <el-button type="text" size="mini" @click="downloadFileList" :loading="downloadFileButton">下载</el-button>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="6" :offset="8">
          <el-row>
            <el-col >
              <el-input size="mini" v-model="searchFile" style="width: 80%" placeholder="请输入文件名称" clearable @clear="clearSearchFile"/>
              <el-button type="primary" plain size="mini" @click="searchFileHandler" @keyup.enter.native="searchFileHandler">搜索</el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-divider></el-divider>
    </el-header>
    <el-main>
      <el-row type="flex" align="middle">
        <el-col v-for="item in fileBreadCrumb" :key="item" :span="1.5">
          <el-button type="text" icon="el-icon-arrow-right" @click="toLastFiles(item)" :disabled="fileBreadCrumb.indexOf(item) + 1 === fileBreadCrumb.length">{{ item | filePathFilter }}</el-button>
        </el-col>
      </el-row>
      <el-table :data="fileList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" />
        <el-table-column label="文件名" prop="fileName" width="720">
          <template slot-scope="scope">
            <el-link v-if="scope.row.fileStatus === 1" :underline="false" @click="toNextFiles(scope.row)">{{ scope.row.fileName }}</el-link>
            <span v-else>{{ scope.row.fileName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="文件大小（MB）" prop="fileSize" :formatter="fileSizeFormat"/>
        <el-table-column label="文件类型" prop="fileStatus" :formatter="statusFormat"/>
        <el-table-column label="最后修改时间" prop="lastModified" :formatter="timeFormat"/>
        <el-table-column label="操作" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="downloadFiles(scope.row)" :loading="downloadFileButton">下载</el-button>
            <el-button type="text" size="mini" @click="toUpdateFileName(scope.row)">修改</el-button>
            <el-button type="text" size="mini" @click="delFiles(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
          title="修改文件夹名称"
          :visible.sync="updateFileNameDialog"
          :append-to-body="true"
          width="30%">
        <el-form :model="oldUpdateFileName" label-width="auto" size="mini">
          <el-form-item label="新文件名：">
            <el-input v-model="updateFileName" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updateFileNames" :loading="updateFileNameButton">确定</el-button>
            <el-button type="info" @click="updateFileNameDialog = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[sizePage, sizePage * 2, sizePage * 4, sizePage * 6]"
          :page-size="sizePage"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalPage">
      </el-pagination>
    </el-main>
  </el-container>
</template>

<script>
import { addFiles, deleteFiles, pageFiles, uploadDir, searchFiles, cdFileDownloadFileList,cdFileDownloadFiles,cdFileUpdateFileName, copyOrCutFile } from "@/api/CdFile";
import {formateDate} from "@/util/TimeFormat";

export default {
  name: "CdFile",
  data(){
    return{
      dirFilesStream: '',
      searchFile: '',
      onFilesPath: '全部文件',
      updateFileName: '',
      uploadFileUrl: process.env.VUE_APP_BASE_API + '/cd_file/upload_file',
      uploadDirUrl: process.env.VUE_APP_BASE_API + '/cd_file/upload_dir',
      operateTab: false,
      uploadDirButton: true,
      createNewFolderDialog: false,
      updateFileNameDialog: false,
      updateFileNameButton: false,
      downloadFileButton: false,
      pasteButton: false,
      pasteButtonLoading: false,
      isCut: false,
      uploadFileButtonLoading: false,
      currentPage: 1,
      sizePage: 10,
      totalPage: 0,
      fileList: [],
      fileBreadCrumb: ['全部文件'],
      selectFileList: [],
      uploadHeaders: { Authorization: sessionStorage.getItem('jwt'), filePath: encodeURIComponent(this.onFilesPath) },
      createNewFolderObj: {},
      oldUpdateFileName: {},
      copyOrCutFileList: [],
    }
  },

  created() {
    this.init()
  },

  filters: {
    filePathFilter(val){
      let s = val.substring(val.lastIndexOf('/') + 1);
      if (s.length > 5){
        return s.substring(0, 6) + '...'
      }else {
        return s
      }
    }
  },

  methods: {

    init(){
      this.getRootList()
      this.initDirUpload()
    },

    fileUploadSuccessHandler(res, file, fileList){
      this.$message.success(res.data.message)
      this.uploadFileButtonLoading = false
      this.getRootList()
    },

    fileUploadErrorHandler(err, file, fileList){
      this.$message.error(err)
      this.uploadFileButtonLoading = false
    },

    fileUploadBeforeHandler(file){
      this.uploadHeaders.filePath = encodeURIComponent(this.onFilesPath)
      this.uploadFileButtonLoading = true
      return true
    },

    createNewFolderCondition(){
      this.createNewFolderObj.filePath = encodeURIComponent(this.onFilesPath)
      this.createNewFolderDialog = true
    },

    createNewFolder(){
      let newFolderObj = this.createNewFolderObj;
      addFiles(newFolderObj).then(res => {
        this.$notify.success(res.data.message)
        this.getRootList()
        this.createNewFolderObj = {}
      }).finally( () => {
        this.createNewFolderDialog = false
      })
    },

    toCopyOrCut(isCut){
      this.isCut = isCut
      this.copyOrCutFileList = this.selectFileList
      if (this.copyOrCutFileList.length > 0){
        if (isCut){
          this.$notify.success('剪切成功')
        }else {
          this.$notify.success('复制成功')
        }
        this.pasteButton = true
      }
    },

    toPaste() {
      this.$confirm('确定粘贴吗？', '粘贴', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.pasteButtonLoading = true
        copyOrCutFile(this.copyOrCutFileList, this.onFilesPath, this.isCut).then(res => {
          if (res.data.code === 20000){
            this.$notify.success(res.data.message)
            this.pasteButton = false
            this.copyOrCutFileList = []
            this.getRootList()
          }else {
            this.$notify.error(res.data.message)
          }
        }).catch(error => {
          this.$notify.error('粘贴失败')
        }).finally(() => {
          this.pasteButtonLoading = false
        })
      } ).catch( () => {
        this.$message.info('取消粘贴')
      } )
    },

    clearSearchFile(){
      this.init()
    },

    initDirUpload(){
      this.$nextTick( () => {
        document.getElementsByClassName('el-upload__input')[1].webkitdirectory = true
      })
    },

    handleSizeChange(val){
      if (this.searchFile){
        searchFiles(this.currentPage, val, this.onFilesPath, this.searchFile).then(res => {
          this.fileList = res.data.data.list
          this.totalPage = res.data.data.total
        }).catch()
      }else {
        pageFiles(this.currentPage, val, this.onFilesPath).then(res => {
          this.fileList = res.data.data.list
          this.totalPage = res.data.data.total
        })
      }

    },
    handleCurrentChange(val){
      if (this.searchFile){
        searchFiles(val, this.sizePage, this.onFilesPath, this.searchFile).then(res => {
          this.fileList = res.data.data.list
          this.totalPage = res.data.data.total
        }).catch()
      }else {
        pageFiles(val, this.sizePage, this.onFilesPath).then(res => {
          this.fileList = res.data.data.list
          this.totalPage = res.data.data.total
        })
      }
    },

    searchFileHandler(){
      searchFiles(this.currentPage, this.sizePage, this.onFilesPath, this.searchFile).then(res => {
        this.fileList = res.data.data.list
        this.totalPage = res.data.data.total
      }).catch()
    },

    downloadFiles(file){
      this.downloadFileButton = true
      cdFileDownloadFiles(file).then(res => {
        let data = res.data;
        let url = window.URL.createObjectURL(new Blob([data], { type: data.type }));
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        let fileName = file.fileName;
        if (file.fileStatus === 1){
          // fileName = fileName.substring(0, fileName.lastIndexOf('.'))
          link.setAttribute('download',  fileName + '.zip');
        }else {
          link.setAttribute('download',  fileName);
        }
        document.body.appendChild(link);
        link.click()
      }).catch( () => {
        this.$notify.error('下载失败')
      } ).finally( () => {
        this.downloadFileButton = false
      } )
    },

    downloadFileList(){
      this.downloadFileButton = true
      cdFileDownloadFileList(this.selectFileList).then(res => {
        let data = res.data;
        let url = window.URL.createObjectURL(new Blob([data], { type: data.type }));
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download',  new Date().getTime() + '.zip');
        document.body.appendChild(link);
        link.click()
      }).catch( () => {
        this.$notify.error('下载失败，有可能是传输管道发生破裂')
      } ).finally( () => {
        this.downloadFileButton = false
      } )
    },

    delFiles(cdFile){
      this.selectFileList.push(cdFile)
      this.$confirm('此操作不可逆，确定删除吗？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then( () => {
        deleteFiles(this.selectFileList).then(res => {
          this.$notify.success(res.data.message)
          this.currentPage = 1
          this.getRootList()
        }).finally( () => {
          this.selectFileList = []
        })
      }).catch( () => {
        this.$message.info('取消删除')
      })

    },

    uploadDirChangeHandler(file, fileList){
      if (fileList.length > 1){
        this.uploadDirButton = false
        this.$message.success('选择成功，请点击 [文件夹上传] 按钮')
      }
    },

    uploadDirHandler(file){
      console.log(file)
      this.dirFilesStream.append('dir', file.file)
    },

    toUpdateFileName(cdFile){
      if (cdFile.fileStatus === 1){
        this.updateFileName = cdFile.fileName
      }else {
        let fileName = cdFile.fileName;
        this.updateFileName = fileName.substring(0, fileName.lastIndexOf('.'))
      }
      this.oldUpdateFileName = cdFile
      this.updateFileNameDialog = true
    },

    updateFileNames(){
      let updateFileName = this.updateFileName;
      let oldUpdateFileName = this.oldUpdateFileName;
      this.updateFileNameButton = true
      cdFileUpdateFileName(oldUpdateFileName, updateFileName).then(res => {
        this.$notify.success(res.data.message)
        this.getRootList()
      }).catch( () => {
        this.$notify.error('修改失败')
      } ).finally( () => {
        this.updateFileNameDialog = false
        this.updateFileNameButton = false
      } )
    },

    submitUploadDir(){
      this.dirFilesStream = new FormData();
      // 调用upload组件的submit函数
      this.$refs.uploadDir.submit()
      this.dirFilesStream.append('filePath', this.onFilesPath)
      uploadDir(this.dirFilesStream).then(res => {
        this.$notify.success(res.data.message)
        this.getRootList()
      }).catch( () => {
        this.$notify.error('上传失败')
      }).finally( () => {
        this.uploadDirButton = true
      })
    },

    async getRootList(){
      await pageFiles(this.currentPage, this.sizePage, this.onFilesPath).then(res => {
        this.currentPage = 1
        this.fileList = res.data.data.list
        this.totalPage = res.data.data.total
      }).finally( () => {
        this.searchFile = ''
      })
    },

    toNextFiles(data){
      this.onFilesPath = data.filePath
      this.getRootList().then(() => {
        this.fileBreadCrumb.push(data.filePath)
        this.currentPage = 1
      }).finally( () => {
        this.searchFile = ''
      })

    },

    toLastFiles(filePath){
      this.onFilesPath = filePath
      this.getRootList().then(() => {
        let deleteIndex = this.fileBreadCrumb.indexOf(filePath) + 1
        let toDeleteIndex = this.fileBreadCrumb.length - deleteIndex
        this.fileBreadCrumb.splice(deleteIndex, toDeleteIndex)
      })

    },

    handleSelectionChange(selection){
      this.selectFileList = selection
      this.operateTab = selection.length > 0;
    },

    timeFormat(row, col, cellValue, index){
      var date = new Date(cellValue * 1000);
      return formateDate(date, "yyyy年MM月dd日")
    },

    statusFormat(row, col, cellValue, index){
      if (cellValue === 1){
        return '文件夹'
      }else {
        const fileName = row.fileName;
        const name = fileName.lastIndexOf('.') + 1
        return fileName.substring(name);
      }
    },

    fileSizeFormat(row, col, cellValue, index){
      if (row.fileStatus === 1){
        return '-'
      }else {
        return cellValue
      }
    },
  }
}
</script>

<style scoped>

</style>
